package sample;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import sample.domain.ExpectedNotice;
import sample.util.DialogType;
import sample.util.HttpUtil;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

public class MainController implements Initializable {

    @FXML
    private Button addBtn;

    @FXML
    private TableView<ExpectedNotice> contentTable;

    @FXML
    private TableColumn<ExpectedNotice, Integer> idColumn;
    @FXML
    private TableColumn<ExpectedNotice, String> keywordColumn;
    @FXML
    private TableColumn<ExpectedNotice, String> companyColumn;
    @FXML
    private TableColumn<ExpectedNotice, String> emailColumn;
    @FXML
    private TableColumn<ExpectedNotice, Integer> actionColumn;

    private ObservableList<ExpectedNotice> expectedNotices;


    public void onAddBtnClick() {
        showAddModifyDialog(DialogType.ADD, null);
    }


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        expectedNotices = getAllNotice();

        contentTable.setItems(expectedNotices);

        idColumn.setCellValueFactory(new PropertyValueFactory<ExpectedNotice, Integer>("id"));
        keywordColumn.setCellValueFactory(new PropertyValueFactory<ExpectedNotice, String>("keyword"));
        companyColumn.setCellValueFactory(new PropertyValueFactory<ExpectedNotice, String>("company"));
        emailColumn.setCellValueFactory(new PropertyValueFactory<ExpectedNotice, String>("email"));
        actionColumn.setCellValueFactory(new PropertyValueFactory<ExpectedNotice, Integer>("id"));

        addBtnToTable();
    }

    private ObservableList<ExpectedNotice> getAllNotice() {
        ObservableList<ExpectedNotice> expectedNotices = FXCollections.observableArrayList();


        String resultString = HttpUtil.getURLString("http://www.taobugou.tech:8990/expected_notice/get_all");
        JSONArray resultArray = JSONArray.parseArray(resultString);
        for (int i = 0; i < resultArray.size(); i++) {
            JSONObject oneNoticeObject = resultArray.getJSONObject(i);

            ExpectedNotice oneNotice = new ExpectedNotice();
            oneNotice.setCompany(oneNoticeObject.getString("company"));
            oneNotice.setEmail(oneNoticeObject.getString("email"));
            oneNotice.setId(oneNoticeObject.getInteger("id"));
            oneNotice.setKeyword(oneNoticeObject.getString("keyword"));

            expectedNotices.add(oneNotice);
        }

        return expectedNotices;
    }


    private void addBtnToTable() {
        actionColumn.setCellFactory(new Callback<TableColumn<ExpectedNotice, Integer>, TableCell<ExpectedNotice, Integer>>() {
            @Override
            public TableCell<ExpectedNotice, Integer> call(TableColumn<ExpectedNotice, Integer> column) {

                TableCell<ExpectedNotice, Integer> cell = new TableCell<ExpectedNotice, Integer>() {
                    Button modifyBtn = new Button("修改");
                    Button deleteBtn = new Button("删除");
                    HBox hBox = new HBox();

                    {
                        modifyBtn.setOnAction(new EventHandler<ActionEvent>() {
                            @Override
                            public void handle(ActionEvent event) {
                                ExpectedNotice notice = getTableView().getItems().get(getIndex());
                                showAddModifyDialog(DialogType.MODIFY, notice);
                            }
                        });

                        deleteBtn.setOnAction(new EventHandler<ActionEvent>() {
                            @Override
                            public void handle(ActionEvent event) {
                                ExpectedNotice notice = getTableView().getItems().get(getIndex());
                                expectedNotices.remove(notice);
                            }
                        });

                        hBox.setAlignment(Pos.CENTER);
                        hBox.getChildren().add(modifyBtn);
                        hBox.getChildren().add(deleteBtn);
                    }

                    @Override
                    protected void updateItem(Integer item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty) {
                            setGraphic(null);
                        } else {
                            setGraphic(hBox);
                        }
                    }
                };
                return cell;
            }
        });
    }

    private void showAddModifyDialog(DialogType type, ExpectedNotice notice) {
        Parent root = null;
        Stage dialogStage = new Stage();
        FXMLLoader loader = new FXMLLoader(getClass().getResource("AddModifyDialog.fxml"));
        try {
            root = loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dialogStage.initModality(Modality.APPLICATION_MODAL);
        dialogStage.setScene(new Scene(root));
        AddModifyDialogController dialogController = loader.getController();
        dialogController.setMainController(this);
        dialogController.setStage(dialogStage);

        if (type == DialogType.MODIFY) {
            dialogController.setNotice(notice);
        }

        dialogStage.show();
    }

    void addNoticeCallBack(ExpectedNotice notice) {
        expectedNotices.add(notice);
    }

    void editNoticeCallBack(ExpectedNotice notice) {
        for (ExpectedNotice oneNotice : expectedNotices) {
            if (oneNotice.getId() == notice.getId()) {
                oneNotice.setCompany(notice.getCompany());
                oneNotice.setKeyword(notice.getKeyword());
                notice.setEmail(notice.getEmail());
                break;
            }
        }
    }
}
